package com.youi.web;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.MultipartFilter;

import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.service.AccesstokenService;
import com.youi.service.ActivitygoodsService;
import com.youi.service.GoodsService;
import com.youi.service.GoodssizeService;
import com.youi.service.SetleaderlevelService;
import com.youi.service.UserService;
import com.youi.third.ali.oss.OSSUtil;
import com.youi.third.wechat.model.AccessToken;
import com.youi.third.wechat.util.MiniAppPoster;
import com.youi.third.wechat.util.WechatUtil;
import com.youi.entity.Accesstoken;
import com.youi.entity.Activitygoods;
import com.youi.entity.Goods;
import com.youi.entity.Goodsimgs;
import com.youi.entity.Goodssize;
import com.youi.entity.User;
import com.yeepay.shade.org.apache.commons.io.output.ByteArrayOutputStream;
import com.youi.common.Common;
import com.youi.util.CommonInfoUtil;
import com.youi.util.DateUtil;
import com.youi.util.FileUploadUtil;
import com.youi.util.JedisUtils;
import com.youi.util.JsonUtil;
import com.youi.util.LogUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.Page;

/**
* 活动商品信息控制层
* @author Administrator
*/
@Controller
public class ActivitygoodsController  extends HttpRequestManage{

		@Autowired
		private ActivitygoodsService activitygoodsService;
		@Autowired
		private UserService userService;
		@Autowired
		private SetleaderlevelService setleaderlevelService;
		@Autowired
		private GoodsService goodsService;
		@Autowired
		private GoodssizeService goodssizeService;
		@Autowired
		private AccesstokenService accesstokenService;
		
		/**
		 * M-32
		 * 查询拼团活动商品列表
		*/
		@ResponseBody
		@RequestMapping("getActivitygoods")
		public String getActivitygoods(ModelMap modelMap,HttpServletRequest request) throws BusinessException,ParseException{
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
			Integer pageIndex=optInteger("pageIndex",request,1);
			Integer pageNum=optInteger("pageNum",request,10);
			String des=optString("des",request,Common.DESC);
			String pms=optString("pms",request);
			Date start=optDate("start",request,"yyyy-MM-dd HH:mm:ss");
			Date end=optDate("end",request,"yyyy-MM-dd HH:mm:ss");
			Map<String, Object> prams=new HashMap<String, Object>();
			prams.put(Common.DELSTATUS, DelStatus.NODEL);
			Map<String, Object> sortPram=new HashMap<String, Object>();
			sortPram.put("sort",des);
			Map<String, Object> searchPram=null;
			if (pms!=null) {
				searchPram=new HashMap<String, Object>();
			}
			Map<String, Object> startTime=null;
			if(start!=null){
				startTime=new HashMap<String, Object>();
				startTime.put(Common.GMTCREATED,start);
			}
			Map<String, Object> endTime=null;
			if(end!=null){
				endTime=new HashMap<String, Object>();
				endTime.put(Common.GMTCREATED,end);
			}
			List<Activitygoods> activitygoodsList=activitygoodsService.getByParamsList(prams, searchPram,sortPram,  (pageIndex-1)*pageNum, pageNum, startTime, endTime);
			if (activitygoodsList==null||activitygoodsList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			Integer pageCount=activitygoodsService.getCountByParamss(prams, searchPram, startTime, endTime);
			modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
			modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);			//pageIndex     查询页数
			modelMap.put(CommonInfoUtil.ALLCOUINT,pageCount);
			activitygoodsService.getGoodsMsg(activitygoodsList);
			modelMap.put(CommonInfoUtil.DATA, ObjectUtil.removeDuplicate(activitygoodsList));		//jsonObjectList json对象集合			
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",modelMap);
		}

		/**
		 * M-43
		 * 根据商品价格计算返回获利
		*/
		@ResponseBody
		@RequestMapping("userGetInfo/getGoodsReturn")
		public String getActivitygoodsById(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
			if (user.getLeaderId()==null) {
				modelMap.put("returnPrice", 0);
				modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
				modelMap.put(CommonInfoUtil.JSONMSG,"操作成功");
				return JsonUtil.toJson(modelMap);
			}
			Double price=getDouble("price", request);
			Double returnPrice=0.00;
			if (user.getLeaderLevel()==1) {
				returnPrice=price*(setleaderlevelService.getLeaderRate(1)*0.01+setleaderlevelService.getLeaderRate(2)*0.01);
			}else if (user.getLeaderLevel()==2) {
				returnPrice=price*(setleaderlevelService.getLeaderRate(2)*0.01);
			}
			modelMap.put("returnPrice", returnPrice);
			modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
			modelMap.put(CommonInfoUtil.JSONMSG,"操作成功");
			return JsonUtil.toJson(modelMap);//jsonObject	json对象
		}

		
		/**
		 * M-33
		 * 生成小程序分享海报
		 * @param modelMap
		 * @param request
		 * @param response
		 * @throws Exception 
		 */
		@RequestMapping("miniAppPoster")
		@ResponseBody
		public String createMiniAppPoster(ModelMap modelMap, HttpServletRequest request,HttpServletResponse response) throws Exception{
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
			Map<String, Object> params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			Map<String, Object> sortParams=new HashMap<String, Object>();
			sortParams.put(Common.ID, Common.DESC);
			Accesstoken accessToken=accesstokenService.getByParam(params, null, sortParams);
			String xcxPath=getString("xcxPath", request);
			Integer type=getInteger(Common.TYPE, request);
			String goodsImgsUrl=optString("goodsImgsUrl", request);
			Long goodsId=optLong("goodsId", request);
			String path="https://image.myjjk.com.cn/myj/miniapp/forever_image/beijing.png";			
			BufferedImage bufferedImage =null;
			if (type==0) {
				if (accessToken==null) {
					AccessToken access_token=WechatUtil.weChatMiniGetAccessToken();
					accessToken=new Accesstoken(access_token.getAccess_token(), String.valueOf(access_token.getExpires_in()));				
					accesstokenService.saveOrUpdate(accessToken);
				}
				bufferedImage = MiniAppPoster.createPoster(accessToken.getAccesstoken(), xcxPath, user.getImg(), path);
				if (bufferedImage==null) {
					AccessToken access_token=WechatUtil.weChatMiniGetAccessToken();
					accessToken=new Accesstoken(access_token.getAccess_token(), String.valueOf(access_token.getExpires_in()));				
					accesstokenService.saveOrUpdate(accessToken);
					bufferedImage=MiniAppPoster.getQrCode(accessToken.getAccesstoken(), xcxPath, 280);
				}
			}else if(type==1) {
				path="https://image.myjjk.com.cn/myj/miniapp/img/20200104/205343846.jpg";
				params=new HashMap<String, Object>();
				params.put(Common.DELSTATUS, DelStatus.NODEL);
				params.put(Common.ID, goodsId);
				Goods goods=goodsService.getByParam(params);
				if (goods==null) {
					return JsonUtil.toJson(CommonInfoUtil.NULLDATA,"商品信息不存在");
				}
				params=new HashMap<String, Object>();
				params.put(Common.DELSTATUS, DelStatus.NODEL);
				params.put("goodsId", goodsId);
				Goodssize goodssize=goodssizeService.getByParam(params);
				if (goodssize==null) {
					return JsonUtil.toJson(CommonInfoUtil.NULLDATA,"商品价格不存在");
				}
				if (accessToken==null) {
					AccessToken access_token=WechatUtil.weChatMiniGetAccessToken();
					accessToken=new Accesstoken(access_token.getAccess_token(), String.valueOf(access_token.getExpires_in()));				
					accesstokenService.saveOrUpdate(accessToken);
				}
				bufferedImage = MiniAppPoster.createPoster(accessToken.getAccesstoken(), xcxPath, user.getImg(), path);
				if (bufferedImage==null) {
					AccessToken access_token=WechatUtil.weChatMiniGetAccessToken();
					accessToken=new Accesstoken(access_token.getAccess_token(), String.valueOf(access_token.getExpires_in()));				
					accesstokenService.saveOrUpdate(accessToken);
				}				
			}	
			ByteArrayOutputStream os = new ByteArrayOutputStream();			
			ImageIO.write(bufferedImage, "jpg", os);			
			byte[] bs=readInputStream(os.toInputStream());		
			String pathUrl=request.getSession().getServletContext().getRealPath("/");
			String returnUrlStr=FileUploadUtil.fileUpload(pathUrl, "code.jpg", bs);
			String url=OSSUtil.upload(bs, "code.jpg");
			modelMap.put("url", url);
			modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
		    modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
		    return JsonUtil.toJson(modelMap);
		}
		
		
		/**
		 * 生成商品二维码海报
		 * @param modelMap
		 * @param request
		 * @param response
		 * @throws Exception 
		 */
		@RequestMapping("createGoodsCode")
		@ResponseBody
		public String createGoodsCode(ModelMap modelMap, HttpServletRequest request,HttpServletResponse response) throws Exception{
			String xcxPath=getString("xcxPath", request);
			Map<String, Object> params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			Map<String, Object> sortParams=new HashMap<String, Object>();
			sortParams.put(Common.ID, Common.DESC);
			Accesstoken accessToken=accesstokenService.getByParam(params, null, sortParams);
			if (accessToken==null) {
				AccessToken access_token=WechatUtil.weChatMiniGetAccessToken();
				accessToken=new Accesstoken(access_token.getAccess_token(), String.valueOf(access_token.getExpires_in()));				
				accesstokenService.saveOrUpdate(accessToken);
			}
			BufferedImage codeImg=MiniAppPoster.getQrCode(accessToken.getAccesstoken(), xcxPath, 280);
			if (codeImg==null) {
				AccessToken access_token=WechatUtil.weChatMiniGetAccessToken();
				accessToken=new Accesstoken(access_token.getAccess_token(), String.valueOf(access_token.getExpires_in()));				
				accesstokenService.saveOrUpdate(accessToken);
				codeImg=MiniAppPoster.getQrCode(accessToken.getAccesstoken(), xcxPath, 280);
			}
			ByteArrayOutputStream os = new ByteArrayOutputStream();			
			ImageIO.write(codeImg, "jpg", os);			
			byte[] bs=readInputStream(os.toInputStream());		
			String pathUrl=request.getSession().getServletContext().getRealPath("/");
			String returnUrlStr=FileUploadUtil.fileUpload(pathUrl, "code.jpg", bs);
			String url=OSSUtil.upload(bs, "code.jpg");
			modelMap.put("url", url);
			modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
		    modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
		    return JsonUtil.toJson(modelMap);
		}
		
		private byte[] readInputStream(InputStream inStream) throws Exception{  
	        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
	        //创建一个Buffer字符串  
	        byte[] buffer = new byte[1024];  
	        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
	        int len = 0;  
	        //使用一个输入流从buffer里把数据读取出来  
	        while( (len=inStream.read(buffer)) != -1 ){  
	            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
	            outStream.write(buffer, 0, len);  
	        }  
	        //关闭输入流  
	        inStream.close();  
	        //把outStream里的数据写入内存  
	        return outStream.toByteArray();  
	    } 
		
}
